<template>
  <div class="container">
    <img
      src="@/assets/img/common/ic_back@2x.png"
      alt=""
      class="backImg"
      @click="$router.back()"
    />
    <!-- <div class="scan_title">{{ $t("scan_scan") }}</div> -->
    <qrcode-stream @decode="onDecode" @init="onInit" ref="qrcodeStream">
      <div class="scanIcon">
        <div class="input_sno" id="snoId">
          <el-input
            clearable
            :placeholder="$t('home_stationID')"
            v-model="params.sno"
            @input="onInput"
            type="tel"
            :maxlength="20"
          ></el-input>
          <img
            src="@/assets/img/common/_@2x.png"
            alt=""
            style="width: 44px; height: 44px; margin-left: 8px"
            @click="getOrdersBillings"
          />
        </div>
        <!-- 图片上传区域 -->
        <div class="upload_section">
          <div class="upload_btn" @click="triggerFileUpload">
            <img
              src="@/assets/img/problem/ic_camera@2x.png"
              alt=""
              class="camera_icon"
            />
            <span class="upload_text">{{ $t('scan_upload_image') }}</span>
          </div>
          <input
            ref="fileInput"
            type="file"
            accept="image/*"
            @change="handleFileUpload"
            style="display: none"
          />
          <!-- 图片预览区域 -->
          <div v-if="uploadedImage" class="image_preview">
            <img :src="uploadedImage" alt="Uploaded image" class="preview_img" />
            <div class="remove_btn" @click="removeImage">
              <img src="@/assets/img/problem/ic_del@2x.png" alt="Remove" />
            </div>
          </div>
        </div>
        <div :style="codeStyle">
          <div class="qr-scanner">
            <div class="box">
              <div class="line"></div>
              <div class="angle"></div>
            </div>
          </div>
        </div>
      </div>
    </qrcode-stream>
    <!-- 低电量提示 -->
    <van-dialog v-model="isShowTip" :showConfirmButton="false">
      <div class="title">{{ $t('Scan_lowPower') }}</div>
      <div class="brief">
        {{ $t('Scan_lowPower_notify').replace('lowPower', maxBc) }}
      </div>
      <div class="btns">
        <div class="btn flex_center" @click="toCancel">
          {{ $t('profile_cancel') }}
        </div>
        <div class="btn flex_center" @click="toRent">
          {{ $t('home_confirm') }}
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import $api from '@/assets/js/api/home'

import share from '@/mixins/share'
export default {
  mixins: [share],
  data () {
    return {
      maxBc: '',
      isShowTip: false,
      snoWidth: '',
      uploadedImage: null,
      uploadedFile: null,
      params: {
        qrUrl: '',
        sno: ''
      },
      windowWidth: document.body.clientWidth
    }
  },
  watch: {
    // 监听页面宽度
    windowWidth (val) {
      // console.log('实时屏幕宽度：', val, this.windowHeight)
      this.getWidth()
    }
  },
  computed: {
    codeStyle () {
      return {
        '--snoWidth': this.snoWidth
      }
    }
  },
  created () {
    this.getLang()
  },
  mounted () {
    this.getWidth()
    window.onresize = () => {
      return (() => {
        this.windowWidth = document.documentElement.clientWidth // 宽
      })()
    }
  },
  methods: {
    toCancel () {
      this.isShowTip = false
    },
    toRent () {
      this.checkIsRent()
    },
    //获取宽度
    getWidth () {
      this.$nextTick(() => {
        let snoId = document.getElementById('snoId')
        this.snoWidth = snoId.clientWidth + 'px'
        // console.log(this.snoWidth)
      })
    },

    //限制输入
    onInput (e) {
      const inputNum = e
      this.params.sno = inputNum.replace(/[^a-zA-Z0-9]/g, '')
    },
    checkIsRent () {
      $api.getUserRent({ sno: this.params.sno }).then(res => {
        this.toCancel()
        if (res.code == 0) {
          // 0:可以租借
          // 1：未交押金
          // 2：有未支付订单
          // 4：租借订单已达上限
          // 9:调查中的订单已达到上限
          localStorage.setItem('device_info', JSON.stringify(this.params))
          if (res.data.rentOrNot == 0) {
            this.$router.push({
              path: '/rent'
            })
          } else if (res.data.rentOrNot == 1) {
            this.$router.push({
              path: '/rent'
            })
          } else if (res.data.rentOrNot == 2) {
            this.global.toast(this.$t('Dialog_HomeRent_Message2'))
          } else if (res.data.rentOrNot == 4) {
            this.global.toast(this.$t('Dialog_HomeRent_Message4'))
          } else if (res.data.rentOrNot == 9) {
            this.global.toast(this.$t('Dialog_HomeRent_Message9'))
          }
        } else {
          this.global.toast(res.message)
        }
      })
    },
    //通过扫码编号获得计费规则
    getOrdersBillings () {
      if (!this.params.sno) {
        this.global.toast(this.$t('toast_enterStationID'))
        return
      }
      $api.getOrdersBilling(this.params).then(res => {
        if (res.code != 0) {
          this.global.toast(res.message)
          return
        }
        if (res.data.code == 0) {
          this.checkIsRent()
        } else if (res.data.code == 1) {
          this.maxBc = res.data.maxBc
          this.isShowTip = true
        } else {
          this.global.toast(res.message)
        }
      })
    },

    // 解码
    onDecode (result) {
      const urlSno = result.includes('https://links.joltzly.com/')
        ? result.replace('https://links.joltzly.com/', '')
        : ''
      const sno =
        urlSno ||
        this.global.getSearchString('sno', result) ||
        this.global.getSearchString('id', result) ||
        ''
      console.log(sno)

      let params = {
        sno: sno,
        qrUrl: result
      }
      this.params = params
      if (!sno) {
        this.global.toast(this.$t('toast_validQRCode'))
        this.$refs.qrcodeStream.reset()
        return
      }
      $api.getOrdersBilling(params).then(res => {
        if (res.code != 0) {
          this.global.toast(res.message)
          return
        }
        if (res.data.code == 0) {
          this.checkIsRent()
        } else if (res.data.code == 1) {
          this.maxBc = res.data.maxBc
          this.isShowTip = true
        } else {
          this.global.toast(res.message)
          this.$refs.qrcodeStream.reset()
        }
      })
    },

    async onInit (promise) {
      try {
        await promise
      } catch (error) {
        let msg = ''
        if (error.name === 'NotAllowedError') {
          msg = this.$t('Error_camera_access')
        } else if (error.name === 'NotFoundError') {
          msg = this.$t('Error_No_camera')
        } else if (error.name === 'NotSupportedError') {
          msg = this.$t('Error_secure_context')
        } else if (error.name === 'NotReadableError') {
          msg = this.$t('Error_camera_inuse')
        } else if (error.name === 'OverconstrainedError') {
          msg = this.$t('Error_camera_improper')
        } else if (error.name === 'StreamApiNotSupportedError') {
          msg = this.$t('Error_streamapi')
        } else if (error.name === 'InsecureContextError') {
          msg = this.$t('Error_camera_permission')
        } else {
          msg = `ERROR: ${$t('Error_camera')} (${error.name})`
        }
        this.global.toast(msg)
      }
    },

    // 触发文件上传
    triggerFileUpload () {
      this.$refs.fileInput.click()
    },

    // 处理文件上传
    handleFileUpload (event) {
      const file = event.target.files[0]
      if (!file) return

      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        this.global.toast(this.$t('scan_upload_image_type_error'))
        return
      }

      // 检查文件大小 (限制为5MB)
      if (file.size > 5 * 1024 * 1024) {
        this.global.toast(this.$t('scan_upload_image_size_error'))
        return
      }

      this.uploadedFile = file
      
      // 创建预览
      const reader = new FileReader()
      reader.onload = (e) => {
        this.uploadedImage = e.target.result
      }
      reader.readAsDataURL(file)
    },

    // 移除图片
    removeImage () {
      this.uploadedImage = null
      this.uploadedFile = null
      this.$refs.fileInput.value = ''
    },

    // 上传图片到服务器
    async uploadImageToServer () {
      if (!this.uploadedFile) return null

      const formData = new FormData()
      formData.append('file', this.uploadedFile)

      try {
        const response = await $api.uploadImg(formData)
        if (response.code === 0) {
          this.global.toast(this.$t('scan_upload_image_success'))
          return response.data.url
        } else {
          this.global.toast(response.message || this.$t('scan_upload_image_failed'))
          return null
        }
      } catch (error) {
        this.global.toast(this.$t('scan_upload_image_failed'))
        return null
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  width: 100%;
  position: relative;
  // opacity: 1;
  background-color: transparent;
  .backImg {
    position: absolute;
    top: 0;
    left: 0;
    width: 44px;
    height: 44px;
    margin-left: 14px;
    z-index: 99;
  }
  .scan_title {
    position: absolute;
    top: 22px;
    left: 50%;
    transform: translate(-50%, -50%);
    font-weight: 600;
    font-size: 16px;
    color: #ffffff;
    z-index: 99;
  }

  .scanIcon {
    padding-top: 122px;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    // opacity: 1;
    // background-color: rgba(0, 0, 0, 0.5);

    .input_sno {
      width: calc(100% - 110px);
      height: 44px;
      margin-left: 55px;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      z-index: 99999;
      .el-input {
        height: 44px !important;
        line-height: 44px !important;
        background: #8a8a89;
        border-radius: 5px;
        color: #ffffff;
      }
      .el-input__inner {
        height: 44px !important;
        line-height: 44px !important;
        background: #8a8a89;
        border-radius: 5px;
        color: #ffffff;
        border: none;
      }
      .el-textarea__inner::placeholder {
        color: #ffffff;
      }
    }

    .upload_section {
      width: calc(100% - 110px);
      margin-left: 55px;
      margin-bottom: 20px;
      position: relative;
      z-index: 99999;

      .upload_btn {
        width: 100%;
        height: 44px;
        background: rgba(138, 138, 137, 0.8);
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;
        border: 1px solid rgba(255, 255, 255, 0.2);

        &:hover {
          background: rgba(138, 138, 137, 1);
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        &:active {
          transform: translateY(0);
        }

        .camera_icon {
          width: 20px;
          height: 20px;
          margin-right: 8px;
          filter: brightness(0) invert(1);
        }

        .upload_text {
          color: #ffffff;
          font-size: 14px;
          font-weight: 500;
        }
      }

      .image_preview {
        margin-top: 10px;
        position: relative;
        display: inline-block;
        animation: fadeIn 0.3s ease-in-out;

        .preview_img {
          width: 100px;
          height: 100px;
          object-fit: cover;
          border-radius: 8px;
          border: 2px solid #ffffff;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }

        .remove_btn {
          position: absolute;
          top: -8px;
          right: -8px;
          width: 24px;
          height: 24px;
          background: #ff4444;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
          transition: all 0.2s ease;

          &:hover {
            background: #ff3333;
            transform: scale(1.1);
          }

          img {
            width: 12px;
            height: 12px;
            filter: brightness(0) invert(1);
          }
        }
      }
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
  }

  .qrcode-stream-wrapper {
    opacity: 1;
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100vh;
    position: relative;
  }

  .qr-scanner .box {
    width: var(--snoWidth) !important;
    height: var(--snoWidth) !important;
    background: url('assets/img/common/scan@2x.png') no-repeat center;
    background-size: cover;
    margin-left: 55px;
    background-color: transparent !important;
    overflow: hidden;
    z-index: 9999;
    position: absolute;
    box-shadow: 0 0 0 200vh rgba(0, 0, 0, 0.9);
  }

  .qr-scanner .line {
    height: calc(100%);
    width: calc(100% - 30px);
    margin-left: 15px;
    border-bottom: 2px solid var(--text-color);
    transform: translateY(-95%);
    animation: radar-beam 2s infinite alternate;
    animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
    animation-delay: 1.4s;
  }

  @keyframes radar-beam {
    0% {
      transform: translateY(-95%);
    }

    100% {
      transform: translateY(-5%);
    }
  }
}
</style>
